package com.datamanage.auth.controller;

import com.datamanage.auth.service.AuthService;
import com.datamanage.user.dto.UserDTO;
import com.datamanage.user.entity.User;
import com.datamanage.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        try {

            String token = authService.authenticate(loginRequest.getUsername(), loginRequest.getPassword());

            Map<String, Object> response = new HashMap<String, Object>();
            response.put("token", token);
            response.put("message", "登录成功");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody UserDTO userDTO) {
        try {
            User user = userService.createUser(userDTO);

            Map<String, Object> response = new HashMap<String, Object>();
            response.put("user", user);
            response.put("message", "注册成功");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        try {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            User user = authService.getCurrentUser(token);

            // 创建一个简化版的用户信息对象，避免序列化复杂的关系对象
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("fullName", user.getFullName());
            userInfo.put("phoneNumber", user.getPhoneNumber());
            userInfo.put("isActive", user.getActive());
            userInfo.put("createdAt", user.getCreatedAt());
            userInfo.put("updatedAt", user.getUpdatedAt());

            // 只添加用户组的基本信息
            if (user.getGroups() != null) {
                userInfo.put("groups", user.getGroups().stream()
                        .map(group -> {
                            Map<String, Object> groupInfo = new HashMap<>();
                            groupInfo.put("id", group.getId());
                            groupInfo.put("name", group.getName());
                            return groupInfo;
                        })
                        .collect(Collectors.toList()));
            }

            // 只添加企业的基本信息
            if (user.getCompany() != null) {
                Map<String, Object> companyInfo = new HashMap<>();
                companyInfo.put("id", user.getCompany().getId());
                companyInfo.put("name", user.getCompany().getName());
                companyInfo.put("companyCode", user.getCompany().getCompanyCode());
                userInfo.put("company", companyInfo);
            }

            Map<String, Object> response = new HashMap<String, Object>();
            response.put("user", userInfo);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 登录请求DTO
    public static class LoginRequest {
        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}